<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>培训计划详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      <el-descriptions class="margin-top" title="基本信息" :column="2" border>
        <el-descriptions-item label="培训名称">{{ planInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="培训类型">{{ getTypeText(planInfo.type) }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ planInfo.startTime | parseTime('{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ planInfo.endTime | parseTime('{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="培训状态">
          <el-tag :type="planInfo.status | statusFilter">{{ planInfo.status | statusTextFilter }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="培训描述">{{ planInfo.description }}</el-descriptions-item>
      </el-descriptions>

      <div class="participants-section">
        <div class="section-header">
          <h3>参训人员</h3>
          <el-button type="primary" size="small" @click="handleAddParticipant">添加人员</el-button>
        </div>
        <el-table :data="participants" border style="width: 100%">
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="department" label="部门" align="center" />
          <el-table-column prop="position" label="职位" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="{row}">
              <el-tag :type="row.status === 'COMPLETED' ? 'success' : 'info'">
                {{ row.status === 'COMPLETED' ? '已完成' : '进行中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="{row}">
              <el-button type="danger" size="mini" @click="handleRemoveParticipant(row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="materials-section">
        <div class="section-header">
          <h3>培训资料</h3>
          <el-button type="primary" size="small" @click="handleUpload">上传资料</el-button>
        </div>
        <el-table :data="materials" border style="width: 100%">
          <el-table-column prop="name" label="文件名" align="center" />
          <el-table-column prop="size" label="大小" align="center">
            <template slot-scope="{row}">
              {{ formatFileSize(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" align="center">
            <template slot-scope="{row}">
              {{ row.uploadTime | parseTime('{y}-{m}-{d}') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleDownload(row)">下载</el-button>
              <el-button type="text" class="delete-button" @click="handleDeleteMaterial(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加参训人员对话框 -->
    <el-dialog title="添加参训人员" :visible.sync="participantDialogVisible" width="50%">
      <el-transfer
        v-model="selectedParticipants"
        :data="employeeList"
        :titles="['可选人员', '已选人员']"
        :props="{
          key: 'id',
          label: 'name'
        }"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="participantDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddParticipants">确定</el-button>
      </div>
    </el-dialog>

    <!-- 上传资料对话框 -->
    <el-dialog title="上传培训资料" :visible.sync="uploadDialogVisible" width="30%">
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传pdf/doc/docx/ppt文件</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { getPlanDetail, addParticipants, removeParticipant, uploadMaterial, deleteMaterial } from '@/api/training'
import { getEmployeeList } from '@/api/employee'

export default {
  name: 'TrainingPlanDetail',
  filters: {
    statusFilter(status) {
      const statusMap = {
        'NOT_STARTED': 'info',
        'IN_PROGRESS': 'success',
        'COMPLETED': 'warning',
        'CANCELLED': 'danger'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        'NOT_STARTED': '未开始',
        'IN_PROGRESS': '进行中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      planInfo: {},
      participants: [],
      materials: [],
      participantDialogVisible: false,
      uploadDialogVisible: false,
      employeeList: [],
      selectedParticipants: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/training/material/upload'
    }
  },
  created() {
    this.getPlanInfo()
    this.getEmployees()
  },
  methods: {
    getPlanInfo() {
      const id = this.$route.params.id
      getPlanDetail(id).then(response => {
        this.planInfo = response.data
        this.participants = response.data.participants || []
        this.materials = response.data.materials || []
      })
    },
    getEmployees() {
      getEmployeeList().then(response => {
        this.employeeList = response.data.map(item => ({
          id: item.id,
          name: `${item.name} - ${item.department}`
        }))
      })
    },
    getTypeText(type) {
      const typeMap = {
        'TECHNICAL': '技术培训',
        'MANAGEMENT': '管理培训',
        'GENERAL': '通用培训'
      }
      return typeMap[type] || type
    },
    formatFileSize(size) {
      if (size < 1024) return size + 'B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB'
      return (size / (1024 * 1024)).toFixed(2) + 'MB'
    },
    handleAddParticipant() {
      this.selectedParticipants = []
      this.participantDialogVisible = true
    },
    confirmAddParticipants() {
      if (this.selectedParticipants.length === 0) {
        this.$message.warning('请选择参训人员')
        return
      }
      addParticipants({
        planId: this.planInfo.id,
        participantIds: this.selectedParticipants
      }).then(() => {
        this.$message.success('添加成功')
        this.participantDialogVisible = false
        this.getPlanInfo()
      })
    },
    handleRemoveParticipant(row) {
      this.$confirm('确认移除该参训人员吗？', '提示', {
        type: 'warning'
      }).then(() => {
        removeParticipant({
          planId: this.planInfo.id,
          participantId: row.id
        }).then(() => {
          this.$message.success('移除成功')
          this.getPlanInfo()
        })
      })
    },
    handleUpload() {
      this.uploadDialogVisible = true
    },
    beforeUpload(file) {
      const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-powerpoint']
      if (!validTypes.includes(file.type)) {
        this.$message.error('只能上传PDF/DOC/DOCX/PPT格式文件！')
        return false
      }
      return true
    },
    handleUploadSuccess() {
      this.$message.success('上传成功')
      this.uploadDialogVisible = false
      this.getPlanInfo()
    },
    handleUploadError() {
      this.$message.error('上传失败')
    },
    handleDownload(row) {
      window.open(row.url)
    },
    handleDeleteMaterial(row) {
      this.$confirm('确认删除该培训资料吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteMaterial(row.id).then(() => {
          this.$message.success('删除成功')
          this.getPlanInfo()
        })
      })
    },
    goBack() {
      this.$router.push('/hr/training/plan')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;

    h3 {
      margin: 0;
    }
  }

  .participants-section,
  .materials-section {
    margin-top: 30px;
  }

  .delete-button {
    color: #f56c6c;
  }

  .el-transfer {
    display: flex;
    justify-content: center;
    margin: 20px 0;
  }
}
</style>